package server;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.Collections;


import domain.PriceStep;
import domain.SortPriceStep;
import exceptions.NoExistingPriceStepException;
import exceptions.OverlappingPriceRangeException;

public class PriceSteps implements Serializable {

	private ArrayList<PriceStep> pricesteps;
	private static PriceSteps instance;
	private static final Object singletonObject = new Object();

	private PriceSteps() {
		pricesteps = new ArrayList<PriceStep>();
	}

	public static PriceSteps getInstance() {
		if(instance == null) {
			synchronized(singletonObject) {
				if(instance==null) {
					instance = new PriceSteps();
				}
			}
		}

		return instance;
	}


	public void add(PriceStep pricestep){
		synchronized(this){
			pricesteps.add(pricestep);
			Collections.sort(pricesteps, new SortPriceStep());
		}
	}

	public void remove(PriceStep pricestep){
		synchronized(this){
			pricesteps.remove(pricestep);
		}
	}

	/* (non-Javadoc)
	 * @see java.lang.Object#toString()
	 */
	@Override
	public String toString() {
		String result = "";
		synchronized(this) {
			result="PriceSteps [pricesteps=" + pricesteps + "]";
		}
		return result;
	}

	public void checkOverlapping(double startPrice, double end) throws OverlappingPriceRangeException {
		synchronized(this) {
			for(PriceStep p : pricesteps) {
				p.checkOverlapping(startPrice,end);
			}
		}
	}

	public void delete(double startPrice, double endPrice) throws NoExistingPriceStepException {

		synchronized(this) {
			for (int i = 0; i < pricesteps.size(); i++) {

				PriceStep p = pricesteps.get(i);
				if(p.getEndPrice() == endPrice && p.getStartPrice() == startPrice){
					pricesteps.remove(p);
				} else {
					throw new NoExistingPriceStepException("No PriceStep!");
				}
			}
		}
	}

	public PriceStep getPriceStep(double price) {
		PriceStep result=null;
		synchronized(this) {
			for (PriceStep priceStep : pricesteps) {
				if((priceStep.minPrice() <= price) && (priceStep.maxPrice() > price)){
					result = priceStep;
				}
			}
		}
		return result;
	}


}
